package controllers;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import services.EventService;
import services.RouteService;
import domain.Event;
import domain.Route;

@Controller
@RequestMapping("/route/administrator")
public class RouteAdministratorController extends AbstractController{

	// Constructors -----------------------------------------------------------

		public RouteAdministratorController() {
			super();
		}

		// Services ---------------------------------------------------------------

		@Autowired
		private RouteService routeService;
		
		@Autowired
		private EventService eventService;


		// Creation ---------------------------------------------------------------

		@RequestMapping(value = "/create", method = RequestMethod.GET)
		public ModelAndView create(@RequestParam int eventId) {
			ModelAndView result;
			Route route;
			
			Event e = eventService.findOne(eventId);
			route = routeService.create(e);
			System.out.println("Llega a crear ruta");
			result = createEditModelAndView(route);
			result.addObject("create", true);
			result.addObject("eventId", route.getEvent().getId());

			return result;
		}

		protected ModelAndView createEditModelAndView(Route route) {
			ModelAndView result;

			result = createEditModelAndView(route, null);

			return result;
		}

		protected ModelAndView createEditModelAndView(Route route, String message) {
			ModelAndView result;
			result = new ModelAndView("route/edit");
			result.addObject("route", route);
			result.addObject("message", message);
			result.addObject("eventId", route.getEvent().getId());
			return result;
		}

		@RequestMapping(value = "/edit", method = RequestMethod.POST, params = "save")
		public ModelAndView save(@Valid Route route, BindingResult binding) {
			ModelAndView result;

			if (binding.hasErrors()) {
				result = createEditModelAndView(route);
				System.out.println(binding.getAllErrors());
				
			} else {
				try {
					routeService.save(route);
					result = new ModelAndView(("redirect:/route/list.do?eventId="+route.getEvent().getId()));
					
					
				} catch (Throwable oops) {
					result = createEditModelAndView(route, "route.commit.error.order");
				}
			}

			return result;
		}

		
}
